import axios, {
  AxiosError,
  type AxiosRequestHeaders,
  type AxiosResponse,
} from "axios";
import pinia from "@/stores/index";
import { Notify } from "vant";

/* 定义response对象的data接口 */
interface ResponseData<T> {
  code: number;
  data: T;
  message: string;
}

// 配置新建一个 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 50000,
});

// 添加请求拦截器
service.interceptors.request.use(config => {
  return config;
});

// 添加响应拦截器
service.interceptors.response.use(
  /* 约束一下response */
  async (response: AxiosResponse<ResponseData<any>>) => {
    // 对响应数据做点什么
    const res = response.data;
  },
  (error: AxiosError) => {
    // 对响应错误做点什么
    if (error.message.indexOf("timeout") != -1) {
      Notify({ type: "danger", message: "网络超时" });
    } else if (error.message == "Network Error") {
      Notify({ type: "danger", message: "网络连接错误" });
    } else {
      if ((error.response as AxiosResponse).data)
        Notify({
          type: "danger",
          message: (error.response as AxiosResponse).statusText,
        });
      else Notify({ type: "danger", message: "接口路径找不到" });
    }
    return Promise.reject(error);
  }
);

export default service;
